/*
 * Copyright 2012 Daniel Kurka
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.googlecode.mgwt.expenses.client.activities.el;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.cellview.client.HasKeyboardPagingPolicy.KeyboardPagingPolicy;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.ProvidesKey;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.googlecode.mgwt.expenses.client.misc.I18N;

public class ExpenseListViewDesktopGwtImpl extends Composite implements ExpenseListView {

	private static ExpenseListViewDesktopGwtImplUiBinder uiBinder = GWT.create(ExpenseListViewDesktopGwtImplUiBinder.class);
	private Presenter presenter;

	interface ExpenseListViewDesktopGwtImplUiBinder extends UiBinder<Widget, ExpenseListViewDesktopGwtImpl> {
	}

	public static class MyCell extends AbstractCell<ExpenseListDTO> {

		public interface Template extends SafeHtmlTemplates {
			@SafeHtmlTemplates.Template("<div style='padding: 5px;'><div style='font-size: 14pt; font-weight: bold;'>{0}</div> <div>Sum: {2}</div> <div>Date: {1} </div></div>")
			SafeHtml content(String title, String date, String amount);

		}

		private static Template TEMPLATE = GWT.create(Template.class);

		@Override
		public void render(com.google.gwt.cell.client.Cell.Context context, ExpenseListDTO value, SafeHtmlBuilder sb) {

			String dateString = I18N.DATE_FORMAT.format(value.getDate());

			SafeHtml content = TEMPLATE.content(value.getTitle(), dateString, I18N.NUMBER_FORMAT.format(value.getAmount()));

			sb.append(content);

		}
	}

	private static class MyKeyProvider implements ProvidesKey<ExpenseListDTO> {

		@Override
		public Object getKey(ExpenseListDTO item) {
			return (item == null) ? null : item.getId();
		}

	}

	@UiField(provided = true)
	CellList<ExpenseListDTO> cellList;

	@UiField
	HTML statusText;

	@UiField
	HTML title;

	private List<ExpenseListDTO> list;
	private SingleSelectionModel<ExpenseListDTO> selectionModel;
	private ListDataProvider<ExpenseListDTO> listDataProvider;

	public ExpenseListViewDesktopGwtImpl() {

		cellList = new CellList<ExpenseListDTO>(new MyCell());

		cellList.setPageSize(30);
		cellList.setKeyboardPagingPolicy(KeyboardPagingPolicy.INCREASE_RANGE);
		cellList.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.BOUND_TO_SELECTION);

		selectionModel = new SingleSelectionModel<ExpenseListDTO>(new MyKeyProvider());

		cellList.setSelectionModel(selectionModel);

		selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
			public void onSelectionChange(SelectionChangeEvent event) {
				Scheduler.get().scheduleDeferred(new ScheduledCommand() {

					@Override
					public void execute() {
						int indexOf = list.indexOf(selectionModel.getSelectedObject());

						if (presenter != null) {
							presenter.onItemSelected(indexOf);
						}

					}
				});

			}
		});

		listDataProvider = new ListDataProvider<ExpenseListDTO>();
		listDataProvider.addDataDisplay(cellList);
		initWidget(uiBinder.createAndBindUi(this));

	}

	@Override
	public void setStatusText(String text) {
		this.statusText.setText(text);

	}

	@Override
	public void setTitleText(String title) {
		this.title.setText(title);

	}

	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;

	}

	@Override
	public void display(List<ExpenseListDTO> list) {

		ArrayList<ExpenseListDTO> arrayList = new ArrayList<ExpenseListDTO>();
		arrayList.addAll(list);

		listDataProvider.setList(arrayList);
		this.list = arrayList;

	}

	@Override
	public void selectItem(int index, boolean selected) {

		selectionModel.setSelected(list.get(index), selected);

	}

	@UiHandler("reloadButton")
	public void onReloadButtonClicked(ClickEvent event) {
		if (presenter != null) {
			presenter.onReloadButtonSelected();
		}
	}

	@UiHandler("createButton")
	public void onCreateButtonClicked(ClickEvent event) {
		if (presenter != null) {
			presenter.onAddButtonSelected();
		}
	}

}
